package org.starapp.plugins.shiro.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.starapp.plugins.shiro.token.ValidateCodeUsernamePasswordToken;
import org.starapp.rbac.exception.ValidateCodeInvalidException;

public class ValidateCodeFormAuthenticationFilter extends
		FormAuthenticationFilter {
	// 创建 Token
	protected ValidateCodeUsernamePasswordToken createToken(
			ServletRequest request, ServletResponse response) {
		String username = getUsername(request);
		String password = getPassword(request);
		String validateCode = WebUtils.getCleanParam(request, "validateCode");
		boolean rememberMe = isRememberMe(request);
		String host = getHost(request);
		return new ValidateCodeUsernamePasswordToken(username, password,
				rememberMe, host, validateCode);

	}

	// 验证码校验
	protected void doCaptchaValidate(HttpServletRequest request,
			ValidateCodeUsernamePasswordToken token) {
		String code = (String) request.getSession()
				.getAttribute("validateCode");
		if (StringUtils.isEmpty(token.getValidateCode())
				|| !StringUtils.equals(code, token.getValidateCode()
						.toLowerCase())) {
			throw new ValidateCodeInvalidException("验证码错误！");
		}
	}

	// 认证
	protected boolean executeLogin(ServletRequest request,
			ServletResponse response) throws Exception {
		ValidateCodeUsernamePasswordToken token = createToken(request, response);
		try {
			doCaptchaValidate((HttpServletRequest) request, token);
			Subject subject = getSubject(request, response);
			subject.login(token);
			return onLoginSuccess(token, subject, request, response);
		} catch (AuthenticationException e) {
			return onLoginFailure(token, e, request, response);
		}

	}

}
